package com.example.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: 15489  <br/>
 * Date: 2022/3/24:11:34  <br/>
 * Description:
 */

@RestController
@RequestMapping("/kill")
public class KillController2 {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @GetMapping("/start2")
    public boolean start(){
//        用老保存秒杀的结果 false表示失败 true表示成功
        boolean flag=false;
//        设置一把锁
        String lock="woniuxy";
//        设置key 的值
        String value= UUID.randomUUID().toString();
        try {
            if(redisTemplate.opsForValue().setIfAbsent(lock,value,10, TimeUnit.SECONDS)){
                //        1：地区redis的库存
                int num=(Integer)redisTemplate.opsForValue().get("num");
//        2:判断库存
                if(num>0){
                    num--;
                    System.out.println("删减库存成功，还剩"+num);
//            修改redis的库存
                    redisTemplate.opsForValue().set("num",num);
                    flag=true;
                }
            }
        }finally {
//
            String getValue=(String)redisTemplate.opsForValue().get(lock);
            if(getValue.equals(value)){
                //            释放redis 锁
                redisTemplate.delete(lock);
            }
        }
        return flag;
    }
}
